<template>
  <div class="shop-container">
    <!-- 搜索和筛选区域合并到一个卡片中 -->
    <div class="search-filter-card">
      <div class="card-content">
        <div class="search-section">
          <div class="search-wrapper">
            <a-input-search
              v-model:value="searchParams.keyword"
              placeholder="搜索商品"
              :style="{ width: '100%' }"
              class="custom-search"
              size="large"
              @search="onSearch"
            >
              <template #enterButton>
                <div class="search-button">
                  <SearchOutlined />
                  搜索
                </div>
              </template>
            </a-input-search>
          </div>
        </div>

        <!-- 筛选区域 -->
        <div class="filter-section">
          <div class="filter-wrapper">
            <!-- 价格区间 -->
            <div class="price-filter">
              <a-space>
                <span class="filter-label">价格：</span>
                <a-input-number
                  v-model:value="searchParams.minPrice"
                  placeholder="最低价"
                  :min="0"
                  style="width: 100px"
                  class="custom-input"
                />
                <span class="price-separator">-</span>
                <a-input-number
                  v-model:value="searchParams.maxPrice"
                  placeholder="最高价"
                  :min="0"
                  style="width: 100px"
                  class="custom-input"
                />
                <a-button
                  type="primary"
                  size="middle"
                  @click="onPriceFilter"
                  class="filter-button"
                >
                  确定
                </a-button>
              </a-space>
            </div>

            <!-- 排序 -->
            <div class="sort-filter">
              <a-radio-group
                v-model:value="sortType"
                @change="onSortChange"
                size="middle"
              >
                <a-radio-button value="default">默认</a-radio-button>
                <a-radio-button value="salesDesc" class="hot-sales-button">
                  <FireOutlined
                    :style="{
                      color: sortType === 'salesDesc' ? '#a5683c' : undefined,
                    }"
                  />
                  热销
                </a-radio-button>
                <a-radio-button value="priceAsc">价格从低到高</a-radio-button>
                <a-radio-button value="priceDesc">价格从高到低</a-radio-button>
              </a-radio-group>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 商品列表区域 -->
    <div class="product-list-container">
      <a-spin :spinning="loading" tip="加载中...">
        <div class="product-grid">
          <a-card
            v-for="product in products"
            :key="product.id"
            :hoverable="true"
            class="product-card"
            @click="goToProductDetail(product.id)"
          >
            <template #cover>
              <div class="product-image-container">
                <img
                  :src="getImageUrl(product.imageUrl)"
                  :alt="product.name"
                  class="product-image"
                  @error="handleImageError"
                />
                <div class="image-overlay">
                  <EyeOutlined class="view-icon" />
                  <span>查看详情</span>
                </div>
              </div>
            </template>
            <a-card-meta>
              <template #title>
                <div class="product-name" :title="product.name">
                  {{ product.name }}
                </div>
              </template>
              <template #description>
                <div class="price-sales">
                  <div class="price">
                    <span class="price-symbol">¥</span>
                    <span class="price-value">{{
                      product.price?.toFixed(2)
                    }}</span>
                  </div>
                  <div class="sales">
                    <ShoppingOutlined style="margin-right: 4px" />
                    {{ product.salesCount || 0 }}
                  </div>
                </div>
              </template>
            </a-card-meta>
          </a-card>
        </div>
      </a-spin>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <a-pagination
          v-model:current="searchParams.current"
          :total="total"
          :pageSize="20"
          show-quick-jumper
          show-size-changer
          :pageSizeOptions="['20', '40', '60', '80']"
          :show-total="showTotal"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { listProductsUsingPost } from "@/api/shangpinjiekou";
import {
  SearchOutlined,
  FireOutlined,
  EyeOutlined,
  ShoppingOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";

interface ClothingProduct {
  id?: number;
  name?: string;
  price?: number;
  imageUrl?: string;
  salesCount?: number;
  description?: string;
  [key: string]: any;
}

const router = useRouter();
const loading = ref(false);
const products = ref<ClothingProduct[]>([]);
const total = ref(0);
const sortType = ref("default");

// 搜索参数
const searchParams = reactive({
  current: 1,
  pageSize: 20, // 固定为20条
  keyword: "",
  minPrice: undefined as number | undefined,
  maxPrice: undefined as number | undefined,
  sortField: "",
  sortOrder: "",
});

// 加载商品列表
const loadProducts = async () => {
  loading.value = true;
  try {
    const res = await listProductsUsingPost(searchParams);
    console.log("API响应:", res);

    // 正确处理嵌套的响应结构
    if (res.data?.code === 0 && res.data?.data) {
      // 检查外层 data 的 code 和 内层 data 是否存在
      products.value = res.data.data.records || []; // 从内层 data 中获取 records
      total.value = Number(res.data.data.total) || 0; // 从内层 data 中获取 total
      console.log("商品数据:", products.value);
      console.log("总数:", total.value);
    } else {
      message.error(res.data?.message || "获取商品列表失败");
    }
  } catch (error) {
    console.error("获取商品列表失败:", error);
    message.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索处理
const onSearch = () => {
  searchParams.current = 1;
  loadProducts();
};

// 价格筛选
const onPriceFilter = () => {
  if (
    searchParams.minPrice &&
    searchParams.maxPrice &&
    searchParams.minPrice > searchParams.maxPrice
  ) {
    message.warning("最低价不能大于最高价");
    return;
  }
  searchParams.current = 1;
  loadProducts();
};

// 排序处理
const onSortChange = () => {
  searchParams.current = 1;
  switch (sortType.value) {
    case "salesDesc":
      searchParams.sortField = "sales";
      searchParams.sortOrder = "desc";
      break;
    case "priceAsc":
      searchParams.sortField = "price";
      searchParams.sortOrder = "asc";
      break;
    case "priceDesc":
      searchParams.sortField = "price";
      searchParams.sortOrder = "desc";
      break;
    default:
      searchParams.sortField = "";
      searchParams.sortOrder = "";
  }
  loadProducts();
};

// 页码改变
const handlePageChange = (page: number) => {
  searchParams.current = page;
  loadProducts();
  window.scrollTo({ top: 0, behavior: "smooth" });
};

// 每页条数改变
const handleSizeChange = (current: number, size: number) => {
  if (current) {
    searchParams.current = 1;
  }
  searchParams.pageSize = size;
  loadProducts();
};

// 跳转到商品详情
const goToProductDetail = (id: number | undefined) => {
  if (id !== undefined) {
    router.push({
      name: "ProductDetail",
      params: { id: id.toString() },
    });
  }
};

// 修改图片路径处理函数
const getImageUrl = (imageUrl: string | undefined) => {
  if (!imageUrl) {
    return new URL(`@/picture/product/default.png`, import.meta.url).href;
  }
  return imageUrl;
};

// 图片加载失败处理函数
const handleImageError = (e: Event) => {
  const img = e.target as HTMLImageElement;
  img.src = new URL(`@/picture/product/default.png`, import.meta.url).href;
};

// 分页组件的 showTotal 函数
const showTotal = (total: number) => `共 ${total} 条`;

onMounted(() => {
  loadProducts();
});
</script>

<style scoped>
.shop-container {
  min-height: 100vh;
  background: url("@/assets/background/homeviewbackground.png") no-repeat center
    top;
  background-size: cover;
  padding: 40px 20px;
  position: relative;
}

.shop-container::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.1);
  z-index: 1;
}

/* 搜索和筛选卡片 */
.search-filter-card {
  max-width: 1200px;
  margin: 0 auto 30px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
  z-index: 10;
  border: 1px solid rgba(165, 104, 60, 0.3);
}

.card-content {
  padding: 30px;
}

.search-section {
  margin-bottom: 20px;
}

.search-wrapper {
  width: 100%;
}

.custom-search :deep(.ant-input-search-button) {
  background-color: #8c4b3c;
  border-color: #8c4b3c;
  height: 40px;
  transition: all 0.3s ease;
}

.custom-search :deep(.ant-input-search-button:hover) {
  background-color: #a5683c;
  border-color: #a5683c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(140, 75, 60, 0.3);
}

.custom-search :deep(.ant-input) {
  height: 40px;
  font-size: 14px;
  border-color: rgba(165, 104, 60, 0.3);
}

.filter-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px dashed rgba(165, 104, 60, 0.3);
}

.filter-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 20px;
}

.price-filter {
  display: flex;
  align-items: center;
}

.filter-label {
  font-size: 14px;
  color: #8c4b3c;
  margin-right: 8px;
  font-weight: 500;
}

.price-separator {
  color: #8c4b3c;
  margin: 0 8px;
}

.custom-input {
  transition: all 0.3s ease;
  border-color: rgba(165, 104, 60, 0.3);
}

.custom-input:hover {
  border-color: #8c4b3c;
}

.filter-button {
  background: #8c4b3c;
  border-color: #8c4b3c;
  transition: all 0.3s ease;
}

.filter-button:hover {
  background: #a5683c;
  border-color: #a5683c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(140, 75, 60, 0.3);
}

.sort-filter :deep(.ant-radio-button-wrapper) {
  border-color: rgba(165, 104, 60, 0.3);
  color: #8c4b3c;
}

.sort-filter :deep(.ant-radio-button-wrapper-checked) {
  color: #fff;
  background: #8c4b3c;
  border-color: #8c4b3c;
}

.sort-filter
  :deep(
    .ant-radio-button-wrapper-checked:not(
        .ant-radio-button-wrapper-disabled
      )::before
  ) {
  background-color: #8c4b3c;
}

.sort-filter :deep(.ant-radio-button-wrapper:hover) {
  color: #a5683c;
}

.product-list-container {
  max-width: 1200px;
  margin: 0 auto;
  background: rgba(255, 255, 255, 0.9);
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;
  border: 1px solid rgba(165, 104, 60, 0.3);
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  background: #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.product-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(165, 104, 60, 0.2);
}

.product-image-container {
  position: relative;
  width: 100%;
  padding-top: 100%;
  overflow: hidden;
}

.product-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.6s ease;
}

.product-card:hover .product-image {
  transform: scale(1.08);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(140, 75, 60, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
}

.product-card:hover .image-overlay {
  opacity: 1;
}

.view-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin: 8px 0;
  line-height: 1.4;
  height: 40px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.price-sales {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.price {
  color: #8c4b3c;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 12px;
  margin-right: 2px;
}

.price-value {
  font-size: 20px;
}

.sales {
  color: #999;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

.pagination-wrapper :deep(.ant-pagination-item-active) {
  border-color: #8c4b3c;
}

.pagination-wrapper :deep(.ant-pagination-item-active a) {
  color: #8c4b3c;
}

.pagination-wrapper :deep(.ant-pagination-item:hover a) {
  color: #a5683c;
}

.pagination-wrapper :deep(.ant-pagination-item:hover) {
  border-color: #a5683c;
}

.hot-sales-button {
  transition: all 0.3s ease;
}

.hot-sales-button:hover .anticon {
  animation: flame 0.8s ease-in-out infinite alternate;
}

@keyframes flame {
  from {
    transform: scale(1);
    opacity: 0.8;
  }
  to {
    transform: scale(1.2);
    opacity: 1;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .product-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 992px) {
  .product-grid {
    grid-template-columns: repeat(3, 1fr);
  }

  .filter-wrapper {
    flex-direction: column;
    align-items: flex-start;
  }

  .sort-filter {
    margin-top: 15px;
    width: 100%;
    overflow-x: auto;
  }
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .card-content {
    padding: 20px;
  }
}

@media (max-width: 576px) {
  .search-wrapper {
    width: 100%;
  }
}
</style>
